import { defineStore } from "pinia";
import { TagViewProps } from '../interface';

// defineStore 调用后返回一个函数，调用该函数获得 Store 实体

export const TagviewStore = defineStore("TagviewStore", {
  // state 类似组件的data选项，函数形式返回对象
  state: () => {
    return {
      visitedViews: [] as any[],
      cachedViews: [] as any[]
    }
  },
  getters: {},
  actions: {
    async AddVisitedView(view: TagViewProps) {
      if (this.visitedViews.some((v: any) => v.path === view.path)) return;
      this.visitedViews.push(
        {
          ...view,
          title: view.meta.title || "no-name"
        }
      );
    },
    async AddCachedView(view: TagViewProps) {
      if (this.cachedViews.includes(view.name)) return;
      if (!view.meta.noCache) {
        this.cachedViews.push(view.name);
      }
    },

    async DelVisitedView(view: TagViewProps) {
      for (const [i, v] of this.visitedViews.entries()) {
        if (v.path === view.path) {
          this.visitedViews.splice(i, 1);
          break;
        }
      }
    },
    async DelCachedView(view: TagViewProps) {
      for (const i of this.cachedViews) {
        if (i === view.name) {
          const index = this.cachedViews.indexOf(i);
          this.cachedViews.splice(index, 1);
          break;
        }
      }
    },

    async DelOthersVisitedViews(view: TagViewProps) {
      this.visitedViews = this.visitedViews.filter(v => {
        return v.meta.affix || v.path === view.path;
      });
    },
    async DelOthersCachedViews(view: TagViewProps) {
      for (const i of this.cachedViews) {
        if (i === view.name) {
          const index = this.cachedViews.indexOf(i);
          this.cachedViews = this.cachedViews.slice(index, index + 1);
          break;
        }
      }
    },

    async DelAllVisitedViews() {
      const affixTags = this.visitedViews.filter(tag => tag.meta.affix);
      this.visitedViews = affixTags;
    },
    async DelAllViews() {
      this.visitedViews = [];
    },
    async DelAllCachedViews() {
      this.cachedViews = [];
    },

    async UpdateVisitedView(view: TagViewProps) {
      for (let v of this.visitedViews) {
        if (v.path === view.path) {
          v = Object.assign(v, view);
          break;
        }
      }
    }
  }
})
